/**
 * @Author: leisure
 * @Date: 2023-09-04 09:00:12
 * @email: cm127214@163.com
 * @Description: 用户存储
 */
import { useOmit } from 'co-utils-vue';
import { defineStore } from 'pinia';

import { getOssStsToken } from '@/api/oss';
import { IOssData } from '@/api/oss/type';
import { userInfo, userLogin, userLogout } from '@/api/user';
import { User } from '@/api/user/type';
import { useGetTokenCookie, useSetTokenCookie } from '@/hooks/use-utils/auth';

export interface IUserInfo extends Partial<User.IUserInfoResponse> {
    isLogin?: boolean;
}

export const useUserStore = defineStore('USER-AUTH', {
  state: () => {
    return {
      userInfo: {} as IUserInfo,
      token: '',
      stsToken: {} as Omit<IOssData, 'userInfo'>
    };
  },
  actions: {
    async reset() {
      this.userInfo = {};
      this.token = '';
      this.stsToken = {} as Omit<IOssData, 'userInfo'>;
    },
    // 用户登录
    getStsToken(): Promise<Omit<IOssData, 'userInfo'>> {
      return new Promise((resolve, reject) => {
        if (Array.from(Object.keys(this.stsToken)).length > 0) {
          resolve(this.stsToken);
        }
        getOssStsToken().then(res => {
          const _res = useOmit(res, ['userInfo']);
          this.stsToken = _res;
          this.userInfo.isLogin = true;
          resolve(_res);
        }).catch(error => {
          reject(error);
        });
      });
    },
    setStsToken(sts: Omit<IOssData, 'userInfo'>) {
      this.stsToken = sts;
    },
    // 用户登录
    login(params: User.ILoginRequest) {
      return new Promise((resolve, reject) => {
        userLogin({
          ...useOmit(params, ['password']),
          password: params.password
        }).then(res => {
          this.token = res.token;
          useSetTokenCookie(res.token);
          this.userInfo.isLogin = true;
          this.getUserInfo();
          resolve(res);
        }).catch(error => {
          reject(error);
        });
      });
    },
    getUserInfo() {
      if (this.userInfo.isLogin && useGetTokenCookie()) {
        userInfo().then(res => {
          Object.assign(this.userInfo, res);
        });
      }
    },
    logout() {
      return new Promise((resolve, reject) => {
        userLogout().then(() => {
          this.token = '';
          this.userInfo = {};
          this.$reset();
          resolve('退出成功');
        }).catch(error => {
          reject(error);
        });
      });
    }
  },
  // 使用该插件，开启数据缓存
  persist: {
    // 这里存储默认使用的是session
    enabled: true,
    strategies: [
      {
        // key的名称
        key: 'USER-AUTH',
        // 更改默认存储，更改为localStorage
        storage: localStorage
        // 默认是全部进去存储, 可以选择哪些进入local存储，这样就不用全部都进去存储了
      }
    ]
  }
});
